package com.dadaguai.controller;

import com.dadaguai.annotation.JwtToken;
import com.dadaguai.common.BusinessException;
import com.dadaguai.common.R;
import com.dadaguai.constants.ResponseCode;
import com.dadaguai.constants.UserConstants;
import com.dadaguai.dto.ForumArticleDto;
import com.dadaguai.dto.UserInfoDto;
import com.dadaguai.service.ForumArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ForumArticleController {

    @Autowired
    ForumArticleService forumArticleService;

    /**
     * 帖子分页查询
     * @param session
     * @param boardId
     * @param sort
     * @param page
     * @param size
     * @param searchField
     * @return
     */
    @GetMapping("/list")
    public R getArticle(HttpSession session, String boardId, String sort, Integer page, Integer size,String searchField) {
        return forumArticleService.getArticleList(session, boardId, sort, page, size,searchField);

    }

    /**
     * 根据id获取帖子信息
     *
     * @param id
     * @return
     * @throws BusinessException
     */

    @GetMapping("/{id}")
    public R getArticleInfo(@PathVariable String id, HttpSession session) throws BusinessException {
        UserInfoDto userInfo = (UserInfoDto) session.getAttribute(UserConstants.USER_INFO_KEY);
        ForumArticleDto article = forumArticleService.getArticleInfo(id, userInfo);
        return R.success(article);
    }

    /**
     * 更新帖子点赞、评论、收藏、分享数
     *
     * @param articleId 帖子id
     * @param type      1=点赞 ；2=评论 ；3=收藏 ； 4=分享
     * @return
     */
    @JwtToken
    @PostMapping("/count")
    public R changeArticleCount(String articleId, Integer type, HttpSession session) {
        UserInfoDto userInfoDto = (UserInfoDto) session.getAttribute(UserConstants.USER_INFO_KEY);
        if (userInfoDto == null) {
            return R.error("用户未登录", ResponseCode.USER_NOT_LOGIN);
        }
        forumArticleService.updateArticleCount(articleId, type, userInfoDto.getUserId());
        return R.success("ok");
    }
}
